import java.util.concurrent.PriorityBlockingQueue;
   class Mytask implements Comparable<Mytask>
   {
       Runnable runnable;
       long nowtime;

       public Mytask(Runnable runnable, long nowtime) {
           this.runnable = runnable;
           this.nowtime = nowtime;
       }

       @Override
       public int compareTo(Mytask o) {
           return (int)(o.nowtime-this.nowtime);
       }

       public void getrun()
       {
           runnable.run();
       }
       public long gettime()
       {
           return nowtime;
       }
   }
class Mytimer{
       //创建一个扫描线程
       public Thread t=null;
       //创建一个优先级队列来存储任务
       public PriorityBlockingQueue<Mytask>m=new PriorityBlockingQueue<>();
    public Mytimer()
    {
         t=new Thread(()->{
           while(true)
           {
               try {
                   //取出当前队列的首元素
                   synchronized (this) {
                       Mytask mytask = m.take();
                       //计算当前的时间戳
                       long curenttime = System.currentTimeMillis();
                       //当前时间和任务执行的时间进行比较，如果还没到任务执行的时间，就将任务放回去，阻塞等待一下，如果到了就执行
                       if (curenttime < mytask.gettime()) {
                           m.put(mytask);
                           this.wait(mytask.gettime() - curenttime);

                       } else {
                           mytask.getrun();
                       }
                   }

               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }

       });
         t.start();

    }
    public void schedule(Runnable runnable,long after)
    {
        //time 表示的是任务执行的时间
        long time=System.currentTimeMillis()+after;
        Mytask mytask=new Mytask(runnable,time);
         //将任务放到队列当中
        m.put(mytask);
        synchronized (this) {
            this.notify();
        }


    }

}


public class Thread79 {
    public static void main(String[] args) {
        Mytimer mytimer=new Mytimer();
        mytimer.schedule(new Runnable(){
            public void run()
            {
                System.out.println("任务1");
            }

        },1000);
        mytimer.schedule(new Runnable(){
            public void run()
            {
                System.out.println("任务2");
            }

        },2000);
    }
}
